package test.shell

import org.junit.Test


class CheckIDNumberTest {

    @Test
    void testCheckIDNumber() {
        assert !checkIDNumber('66666688888883331')
    }

    /**
     * 检测身份证号
     */
    private boolean checkIDNumber(String id_num) {
        def b = (~/^\d{17}[0-9xX]$/).matcher(id_num).matches()
        if (!b) return false
        def w = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        def c = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
        def s = 0
        for (i in 0..<17) {
            s += (id_num.charAt(i) - (char) '0') * w[i]
        }
        def r = c[s % 11]
        def e = id_num.charAt(17)
        return (e == r || e == 'x' && r == 'X')
    }

    /**
     * 检测身份证号 - groovy代码，用GroovyShell调用
     */
    @Test
    void testByGroovyShell() {
        String code = """
boolean checkIDNumber(String id_num) {
    def b = (~/^\\d{17}[0-9xX]\$/).matcher(id_num).matches()
    if (!b) return false
    def w = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
    def c = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
    def s = 0
    for (i in 0..<17) {
        s += (id_num.charAt(i) - (char) '0') * w[i]
    }
    def r = c[s % 11]
    def e = id_num.charAt(17)
    return (e == r || e == 'x' && r == 'X')
}
return checkIDNumber('66666688888883331') == false
"""
        def shell = new GroovyShell(new GroovyClassLoader())
        def loadedScript = shell.parse(code)
        assert loadedScript.run()
    }
}
